package logic

import (
	"context"
	"errors"
	"pro-shop-manager/models/cache"
	"pro-shop-manager/models/mysql"
	"pro-shop-manager/pkg"

	"pro-shop-manager/userrpc/internal/svc"
	"pro-shop-manager/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录与注册
func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()

	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误")
	}

	result1, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

	if result1 != in.SendSmsCode {
		return nil, errors.New("短信验证码错误")
	}

	if err := user.UserFindByName(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("该用户不存在")
	}

	user = mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}

	if err := user.UserAdd(mysql.DB); err != nil {
		return nil, err
	}

	return &userrpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
